<template>
  <div>
    <el-container class="elContainer">
      <el-header class="d-flex align-items-center">
        <div class="d-flex mr-auto align-items-center">
          <el-select
            class="mr-2"
            v-model="searchForm.order"
            placeholder="请选择图片排序方式"
            size="medium"
            style="width: 200px"
          >
            <el-option
              v-for="(item, index) in searchForm"
              :key="index"
              :label="item.order"
              :value="item.keywords"
            >
            </el-option>
          </el-select>
          <el-input
            class="mr-2"
            style="width: 200px"
            placeholder="请输入相册名称"
            v-model="searchForm.keywords"
          ></el-input>
          <el-button type="success" size="medium">搜索</el-button>
        </div>
        <el-button type="warning" size="medium" @click="unChoose" v-show="chooseList.length">取消选择</el-button>
        <el-button type="danger" size="medium" @click="delImage({all:true})" v-show="chooseList.length">批量删除</el-button>
        <el-button type="success" size="medium" @click="openAlbumsModal(false)"
          >创建相册</el-button
        >
        <el-button type="warning" size="medium" @click="openUploadModal"
          >上传图片</el-button
        >
      </el-header>
      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="200px" class="elAside bg-white border-right">
          <ul class="list-group list-group-flush">
            <li
              class="list-group-item d-flex align-items-center"
              :class="{ 'sum-active': index === albumIndex }"
              @click.stop="changeAlbum(index)"
              v-for="(item, index) in album"
              :key="index"
            >
              {{ item.name }}
              <el-dropdown :hide-on-click="false" class="ml-auto">
                <span class="btn btn-light btn-sm border">
                  {{ item.order
                  }}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    @click.stop.native="openAlbumsModal({ item, index })"
                    >修改</el-dropdown-item
                  >
                  <el-dropdown-item @click.stop.native="albumsDel({index})"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </li>
          </ul>
        </el-aside>
        <!-- 主体内容部分 -->
        <el-container class="mainContainer">
          <el-main>
            <!-- 相册主内容 -->
            <el-row :gutter="10">
              <el-col :span="24" :lg="4" :md="6" :sm="8" v-for="(item, index) in imgList"  :key="index">
                <el-card
                  class="box-card mb-3 position-relative"
                  :body-style="{ padding: 0 }" style="cursor:pointer">
                  <div class="border" style="height:140px" :class="{'border-danger' : item.isCheck}">
                    <span class="badge badge-danger position-absolute" v-show="item.isCheck"
                    style="right:0;top:0">{{item.checkOrder}}</span>
                    <div style="height:100px">
                      <img :src="item.url" class="w-100" style="height: 100px;margin-top:-65px;"
                      @click="chooseImage(item)"/>
                      <div class="w-100 imgText">{{item.name}}</div>
                    </div>
                    <el-button-group class="btnGroup w-100">
                      <el-button icon="el-icon-view" size="mini" @click="previewImg(item)"
                      ></el-button>
                      <el-button icon="el-icon-edit" size="mini" @click="editImage(item,index)"></el-button>
                      <el-button icon="el-icon-delete" size="mini" @click="delImage(index)"></el-button>
                    </el-button-group>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <!-- /相册主内容 -->
          </el-main>
        </el-container>
      </el-container>
      <el-footer class="d-flex align-items-center p-0 border-top">
        <div class="border-right" style="width:200px">
          <el-button-group>
            <el-button size="mini">&lt;上一页</el-button>
            <el-button size="mini">下一页&gt;</el-button>
          </el-button-group>
        </div>
        <div class="pl-2" style="margin-top:35px">
          <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="400">
        </el-pagination>
        </div>
      </el-footer>
    </el-container>

    <!-- 修改|创建相册对话框 -->
    <el-dialog
      :title="createAlbumIndex == -1 ? '创建相册' : '修改相册'"
      :visible.sync="albumVisible"
    >
      <div>
        <el-form
          ref="form"
          :model="albumForm"
          label-width="80px"
          :rules="rules"
        >
          <el-form-item label="相册名称" prop="name">
            <el-input
              v-model="albumForm.name"
              placeholder="请输入相册名称"
              size="medium"
            ></el-input>
          </el-form-item>
          <el-form-item label="相册排序" prop="order">
            <el-input-number
              v-model="albumForm.order"
              :min="1"
              label="排序"
              size="medium"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="albumVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirmAlbum">确 定</el-button>
      </div>
    </el-dialog>
    <!-- /修改|创建相册对话框 -->
    <!-- 上传图片 -->
    <el-dialog title="上传图片" :visible.sync="uploadModal" width="50%">
      <div class="upLoad">
        <el-upload
          class="upload-demo"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </div>
    </el-dialog>
    <!-- /上传图片 -->
    <!-- 预览图片 -->
    <el-dialog :visible.sync="previewModal">
      <div style="margin: -60px;-20px;-40px;-20px">
        <img
          :src="previewImage"
          class="w-100"
        />
      </div>
    </el-dialog>
    <!-- /预览图片 -->
    <!-- 修改图片名称 -->
    <!-- /修改图片名称 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchForm: [
        {
          order: "排序1",
          keywords: "黄金糕",
        },
        {
          order: "排序2",
          keywords: "双皮奶",
        },
      ],
      album: [],
      albumIndex: 0,
      albumVisible: false,
      albumForm: {
        name: "",
        order: 0,
      },
      createAlbumIndex: -1,
      rules: {
        name: [{ required: true, message: "请输入相册名", trigger: "blur" }],
        order: [
          { required: true, message: "请输入序号", trigger: "blur" },
          {
            pattern: /^[0-9]{1,15}$/,
            message: "序号不符合要求",
            trigger: "blur",
          },
        ],
      },
      uploadModal: false,
      previewModal: false,
      imgList: [],
      previewImage: '',
      currentPage: 1,
      // 选择图片的数组
      chooseList: []
    };
  },
  components: {},
  props: {},
  created() {
    this.__initAlbum();
  },
  computed: {},
  watch: {},
  methods: {
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
    // 删除图片
    delImage(obj) {
      this.$confirm(obj.all ? '是否批量删除图片？':'是否要删除该图片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 批量删除图片
        if (obj.all) {
          let list = this.imgList.filter(v => {
            return v.isCheck === false
          })
          this.imgList = list
          this.chooseList = []
        } else {
          // 删除当前图片
          this.imgList.splice(obj, 1)
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改图片名称
    editImage(item,index) {
        this.$prompt('请输入新名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: item.name,
          inputValidator(val) {
            if (val == '') {
              return '图片名不能为空'
            }
          }
        }).then(({ value }) => {
          item.name = value,
          this.$message({
            type: 'success',
            message: '新名称是: ' + value
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
    },
    // 预览图片
    previewImg(item) {
      this.previewImage = item.url
      this.previewModal = true;
    },
    // 上传图片对话框
    openUploadModal() {
      this.uploadModal = true;
    },
    // 打开相册对话框
    openAlbumsModal(obj) {
      if (obj) {
        let { item, index } = obj;
        this.albumForm.name = item.name;
        this.albumForm.order = item.order;
        this.createAlbumIndex = index;
        return (this.albumVisible = true);
      }
      // 创建
      this.albumForm = {
        name: "",
        order: 0,
      };
      this.createAlbumIndex = -1;
      this.albumVisible = true;
    },
    onConfirmAlbum() {
      // 先验证输入内容是否满足要求
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        if (this.createAlbumIndex > -1) {
          this.editAlbum();
          return (this.albumVisible = false);
        }
        this.album.unshift({
          name: this.albumForm.name,
          order: this.albumForm.order,
        });
        this.albumVisible = false;
      });
    },
    // 修改相册
    editAlbum() {
      this.album[this.createAlbumIndex].name = this.albumForm.name;
      this.album[this.createAlbumIndex].order = this.albumForm.order;
    },
    // 删除左侧相册
    albumsDel(index) {
      this.$confirm("是否删除该相册?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除成功
          this.album.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击切换相册
    changeAlbum(index) {
      this.albumIndex = index;
    },
    // 初始化相册
    __initAlbum() {
      let arr = [];
      for (let index = 0; index < 20; index++) {
        arr.push({
          name: "相册" + index,
          order: Math.floor(Math.random() * 100),
        });
      }
      this.album = arr;
      // 生成相片列表
      for (let index = 0; index < 20; index++) {
        this.imgList.push({
          id: index,
          url: 'https://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/Appstatic/qsbk/demo/datapic/40.jpg',
          name: '图片' + (index + 1 - 0),
          isCheck: false,
          checkOrder: 0
        })
      }
    },
    chooseImage(item) {
      // 未选中
      if (!item.isCheck) {
          this.chooseList.push({
          id: item.id,
          url: item.url
          })
          item.isCheck = true
          item.checkOrder = this.chooseList.length
          return
      }
      // 已选中
      // 找到取消选中的index
      let i = this.chooseList.findIndex(v => v.id === item.id)
      if (i === -1) return
      // 重新计算序号
      let length = this.chooseList.length
      if (i + 1 < length) {
        // 从第i个开始循环 后面的才需要重新计算序号
        for (let j = i; j < length; j++) {
          let no = this.imgList.findIndex(v => v.id === this.chooseList[j].id)
          if (no > -1) {
            this.imgList[no].checkOrder--
          }
        }
      }
      // 重新计算数组长度
      this.chooseList.splice(i,1)
      item.isCheck = false
      item.checkOrder = 0
    },
    // 取消选择图片
    unChoose() {
      this.imgList.forEach(img => {
        // 找到选择列表有的图片的索引
        let i = this.chooseList.findIndex(v => {
          return v.id === img.id
        })
        if (i > -1) {
          // 从选择列表中删除
          this.chooseList.splice(i,1)
          img.isCheck = false
          img.checkOrder = 0
        }
      })
    }
  },
};
</script>
<style lang="less" scoped>
.el-header,
.el-footer {
  text-align: center;
  line-height: 60px;
}

.el-aside {
  text-align: center;
}

.el-main {
  text-align: center;
  line-height: 160px;
}
.elContainer {
  position: absolute;
  top: 55px;
  left: 0;
  right: 0;
  bottom: 0;
}
.elAside {
  position: absolute;
  top: 60px;
  bottom: 60px;
  left: 0;
}
.mainContainer {
  position: absolute;
  top: 60px;
  bottom: 60px;
  left: 200px;
  right: 0;
}
.sum-active {
  color: #67c23a !important;
  background-color: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}
.upLoad {
  text-align: center;
}
.imgText {
  position: absolute;
  top:77px;
  text-align: left;
  padding-left: 10px;
  color: white;
  background: rgba(0, 0, 0, 0.5);
  height: 25px;
  line-height: 25px;
}
.btnGroup {
  position: absolute;
  left: 5px;
  top: 105px;
}
</style>
